package com.rabbit.config;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <h1>RestTemplate相关配置</h1>
 *
 * @author zjw
 * @date 2021/7/1 15:29
 */
@Configuration
@EnableConfigurationProperties(RestTemplateProperties.class)
@ConditionalOnProperty(name = "spring.http.enable", havingValue = "true")
public class RestTemplateConfig {

    @Bean
    public RestTemplate getRestTemplate(RestTemplateProperties properties) {
        RestTemplate restTemplate = new RestTemplate(createFactory(properties));
        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();

        //重新设置StringHttpMessageConverter字符集为UTF-8，解决中文乱码问题
        HttpMessageConverter<?> converterTarget = null;
        for (HttpMessageConverter<?> item : converterList) {
            if (StringHttpMessageConverter.class == item.getClass()) {
                converterTarget = item;
                break;
            }
        }
        if (null != converterTarget) {
            converterList.remove(converterTarget);
        }
        converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }

    private ClientHttpRequestFactory createFactory(RestTemplateProperties properties) {
        HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(properties.getMaxTotalConnect())
                .setMaxConnPerRoute(properties.getMaxConnectPerRoute()).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        factory.setConnectTimeout(properties.getConnectTimeout());
        factory.setReadTimeout(properties.getReadTimeout());
        factory.setConnectionRequestTimeout(properties.getConnectionRequestTimeOut());
        return factory;
    }

}
